package com.xiaomazi.edu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.edu.excel.SubjectData;
import com.xiaomazi.edu.listener.ExcelListener;
import com.xiaomazi.edu.vo.SubjectResult;
import com.xiaomazi.edu.vo.TwoSubject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaomazi.edu.mapper.SubjectMapper;
import com.xiaomazi.edu.entity.Subject;
import com.xiaomazi.edu.service.SubjectService;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService{
    /**
     * 获取全部分类数据 一个一级分类包含多个二级分类
     * @return list
     */
    @Override
    public R getAllSubject() {
        List<SubjectResult> resultList = new ArrayList<>();

        List<Subject> oneSubjects = this.query().eq("parent_id", "0").list();

        List<Subject> twoSubjects = this.query().ne("parent_id", "0").list();

        for (Subject oneSubject : oneSubjects) {
            SubjectResult subjectResult = new SubjectResult();
            BeanUtil.copyProperties(oneSubject,subjectResult);
            List<TwoSubject> twoSubjectList = subjectResult.getTwoSubjectList();
            for (Subject twoSubject : twoSubjects) {
                if (twoSubject.getParentId().equals(oneSubject.getId())){
                    TwoSubject twoSubject1 = BeanUtil.copyProperties(twoSubject, TwoSubject.class);
                    twoSubjectList.add(twoSubject1);
                }
            }
            subjectResult.setTwoSubjectList(twoSubjectList);
            resultList.add(subjectResult);
        }

        return R.ok().data("list",resultList);
    }

    /**
     * 通过上传excel来添加课程分类
     * @param excelFile
     * @return
     */
    @Override
    public R saveSubjectByExcel(MultipartFile excelFile) {
        try {
            InputStream stream = excelFile.getInputStream();
            //调用方法进行读取
            EasyExcel.read(stream, SubjectData.class,new ExcelListener(this)).sheet().doRead();
            return R.ok();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
